import 'dart:async';

import 'package:flutter/material.dart';

class CounterHome extends StatelessWidget {
  const CounterHome({super.key});

  @override
  Widget build(BuildContext context) {
    CounterBloc _counterBloc = CounterProvider.of(context).bloc;

    return Center(
      child: StreamBuilder(
      initialData: 0,
      stream: _counterBloc.count,
      builder: (context, snapshot) {
        return ActionChip(
          label: Text('${snapshot.data}'),
          onPressed: () {
            // _counterBloc.log();
            _counterBloc.counter.add(1);
          },
        );
      },
    ));
  }
}

class CounterActionButton extends StatelessWidget {
  const CounterActionButton({super.key});

  @override
  Widget build(BuildContext context) {
    CounterBloc _counterBloc = CounterProvider.of(context).bloc;

    return FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {
        _counterBloc.log();
      },
    );
  }
}

class CounterProvider extends InheritedWidget {
  final Widget child;
  final CounterBloc bloc;

  CounterProvider({required this.child, required this.bloc})
      : super(child: child);

  static CounterProvider of(BuildContext context) =>
      context.dependOnInheritedWidgetOfExactType<CounterProvider>()!;

  @override
  bool updateShouldNotify(covariant InheritedWidget oldWidget) {
    return true;
  }
}

class CounterBloc {
  int _count = 1;

  final _counterActionCountroller = StreamController<int>();
  StreamSink<int> get counter => _counterActionCountroller.sink;

  final _counterCountroller = StreamController<int>();
  Stream<int> get count => _counterCountroller.stream;

  CounterBloc() {
    _counterActionCountroller.stream.listen(onData);
  }

  void onData(int data) {
    print('$data');
    _count = data + _count;
    _counterCountroller.add(_count);
  }

  void disponse() {
    _counterActionCountroller.close();
    _counterCountroller.close();
  }

  void log() {
    print('BLoC');
  }
}
